import { observable, action, toJS } from 'mobx';
import { message, Modal } from 'antd';
import { WeaLocaleProvider, WeaTools } from 'ecCom';
import _ from 'lodash';
const getLabel = WeaLocaleProvider.getLabel;
const formatMultiLang = WeaLocaleProvider.formatMultiLang;
import { getDataCondition } from "../../apis/dataset";
import FieldPropsStore from '../excel/FieldPropsStore';
import $ from "jquery";
import React from 'react';

export default class ConditionDialogStore {
    @observable type = "";
    @observable visable = false;
    @observable conditions = {};
    @observable conditionParam = {};//条件参数
    @observable initParam = {};//初始化参数
    @observable conditionInfo = {};
    @observable conditionField = {};
    @observable relationtypeOptions = [];
    @observable fieldRecord = {};
    @observable relation = "4";//等于
    @observable targetValue = "";//值
    @observable targetValueSpan = "";//显示名称
    @observable newValue = "";//值
    @observable newValueSpan = "";//显示名称
    @observable valuetype = "";//变量类型
    @observable targetValueOptions = {};//表格变量字段下拉数据源
    @observable ismodified = "0";//是否修改了
    @observable dbtype = "";//数据库类型
    @observable root = {};
    @observable selectedItemKey = [];
    @observable editArr = [];//处于编辑状态的数据
    @observable selectedItemParentNode = "";
    @observable ruleSql = "";
    @observable ruleSqlText = "";
    @observable isShowSql = false;
    @observable contentHeight = 300;
    @observable isNeedClose = false;//是否需要关闭dialog
    @observable isChange = false;//顶部条件是否改变
    @observable refObj = {};
    @observable fieldPropsStore;
    @observable tableOptions = [];

    @action
    onSave = () => {
        const { conditiontype, conditionsql2 } = this.conditionInfo;
        if (conditiontype == 1) {
            if (this.editArr.length > 0) {
                message.error(getLabel('513499','存在字段处于编辑状态，请编辑好后再进行保存操作'));
                return;
            }
            if (this.isChange == true && this.targetValue != "") {
                let doSaveCondition = this.doSaveCondition;
                Modal.confirm({
                    title: getLabel('513500','当前目标字段的值未添加到条件中，是否继续保存'),
                    onOk: () => {
                        doSaveCondition();
                    },
                    onCancel() { },
                });
            } else {
                this.doSaveCondition();
            }

        } else {
            if (_.trim(formatMultiLang(conditionsql2)) == "") {
                for (let key in this.refObj) {
                    if (key == "sql_") {
                        const domkeyRef = this.refObj[key];
                        domkeyRef.showError();
                        return;
                    }
                }
            }
            const cellType = this.fieldPropsStore.cellType();
            cellType.conditionInfo = {
                conditionsql2: conditionsql2,
                conditiontype: conditiontype
            };
            this.isNeedClose = false;
            this.conditionSaveCallBack();
        }

    }

    @action
    doSaveCondition = () => {
        this.getShowSql();
        if (this.ruleSql == "") {
            message.error(getLabel(15364, "条件") + getLabel('513479','不能为空!'));
            return;
        }
        const cellType = this.fieldPropsStore.cellType();
        cellType.conditionInfo = {
            root: this.root,
            conditionsql: this.ruleSql,
            conditiontext: this.ruleSqlText,
            conditiontype: "1"
        };
        this.isNeedClose = false;
        this.conditionSaveCallBack();
    }

    @action
    deleteCondition = () => {
        this.isNeedClose = true;
        Modal.confirm({
            title: getLabel('515714', '确定清空所有条件？'),
            onOk: () => {
                const cellType = this.fieldPropsStore.cellType();
                cellType.conditionInfo = {
                    root: "",
                    conditionsql: "",
                    conditiontext: "",
                    conditiontype: this.conditiontype
                };
                this.conditionSaveCallBack();
                this.parent().reEnterCell();
            },
            onCancel() { },
        });
    }

    /**
	 * 条件保存后回调函数
	 */
    @action
    conditionSaveCallBack = () => {
        message.success(getLabel(83885, "操作成功!"));
        if (this.isNeedClose) {
            this.visable = false;
        }
    }


    @action
    getShowSql = () => {
        let sql = "";
        let sqlText = "";
        if (this.root.key && this.root.key > 0) {
            let obj = this.getSql(this.root, { sql: "", sqlText: "" });
            sql = obj.sql;
            sqlText = obj.sqlText;
        }
        this.ruleSql = sql;
        this.ruleSqlText = sqlText;
    }

    @action
    getSql = (item, { sql, sqlText }) => {
        const { isParent } = item;
        if (isParent) {
            const { datas, relationship } = item;
            let relation = "AND"
            if (relationship == "0") {
                relation = "OR";
            }
            for (let i = 0; i < datas.length; i++) {
                if (i > 0) {
                    sql += " " + relation + " ";
                    sqlText += " " + relation + " ";
                }
                if (datas.length > 1 && i == 0) {
                    sql += "(";
                    sqlText += "(";
                }
                let obj = this.getSql(datas[i], { sql: "", sqlText: "" });
                sql += obj.sql;
                sqlText += obj.sqlText;
                if (datas.length > 1 && i == datas.length - 1) {
                    sql += ")";
                    sqlText += ")";
                }
            }
        } else {
            const { compareopion, tablename, fieldname, htmltype, fieldtype, fieldvalue, fieldlabel, fieldtext } = item;
            let relationAndVal = "";
            let text = "";
            if (fieldvalue == "null" && (htmltype == 5 || htmltype == 4)) {//select或者checkbox 框为null
                if (compareopion == 4) {//等于
                    relationAndVal = " is null ";
                } else if (compareopion == 5) {//不等于
                    relationAndVal = " is not null ";
                } else if (compareopion == 6) {//包含
                    relationAndVal = " is null ";
                } else {//不包含
                    relationAndVal = " is not null ";
                }
                text = relationAndVal;
                sql += tablename + "." + fieldname + " " + relationAndVal;
                sqlText += fieldlabel + " " + text;
            } else {
                if ((htmltype == 5 && fieldtype == 2) || (htmltype == "3" && (fieldtype == "17" || fieldtype == "18" || fieldtype == "37" || fieldtype == "57" || fieldtype == "65" || fieldtype == "135" || fieldtype == "152" || fieldtype == "162"
                    || fieldtype == "166" || fieldtype == "168" || fieldtype == "170" || fieldtype == "184" || fieldtype == "194" || fieldtype == "257" || fieldtype == "261"
                    || fieldtype == "269" || fieldtype == "278"))) {
                    let fieldvaluevar = fieldvalue.split(",");
                    if (compareopion == 6) {//包含
                        for (let i = 0; i < fieldvaluevar.length; i++) {
                            if (i == 0) {
                                if (this.dbtype == "mysql") {
                                    relationAndVal += " concat(','," + tablename + "." + fieldname + ",',') like '%," + fieldvaluevar[i] + ",%'";
                                }
                                if (this.dbtype == "oracle" || this.dbtype == "db2") {
                                    relationAndVal += " ','||" + tablename + "." + fieldname + "||',' like '%," + fieldvaluevar[i] + ",%'";
                                }
                                if (this.dbtype == "sqlserver") {
                                    relationAndVal += " ','+isnull(cast(" + tablename + "." + fieldname + " as varchar(4000)),'')+',' like '%," + fieldvaluevar[i] + ",%'";
                                }
                            } else {
                                if (this.dbtype == "mysql") {
                                    relationAndVal += " AND concat(','," + tablename + "." + fieldname + ",',') like '%," + fieldvaluevar[i] + ",%'";
                                }
                                if (this.dbtype == "oracle" || this.dbtype == "db2") {
                                    relationAndVal += " AND ','||" + tablename + "." + fieldname + "||',' like '%," + fieldvaluevar[i] + ",%'";
                                }
                                if (this.dbtype == "sqlserver") {
                                    relationAndVal += " AND ','+isnull(cast(" + tablename + "." + fieldname + " as varchar(4000)),'')+',' like '%," + fieldvaluevar[i] + ",%'";
                                }
                            }
                        }
                        text = " like " + "'%" + fieldtext + "%'";
                    } else if (compareopion == 7) {//不包含
                        for (let i = 0; i < fieldvaluevar.length; i++) {
                            if (i == 0) {
                                if (this.dbtype == "mysql") {
                                    relationAndVal += " concat(','," + tablename + "." + fieldname + ",',') not like '%," + fieldvaluevar[i] + ",%'";
                                }
                                if (this.dbtype == "oracle" || this.dbtype == "db2") {
                                    relationAndVal += " ','||" + tablename + "." + fieldname + "||',' not like '%," + fieldvaluevar[i] + ",%'";
                                }
                                if (this.dbtype == "sqlserver") {
                                    relationAndVal += " ','+isnull(cast(" + tablename + "." + fieldname + " as varchar(4000)),'')+',' not like '%," + fieldvaluevar[i] + ",%'";
                                }
                            } else {
                                if (this.dbtype == "mysql") {
                                    relationAndVal += " AND concat(','," + tablename + "." + fieldname + ",',') not like '%," + fieldvaluevar[i] + ",%'";
                                }
                                if (this.dbtype == "oracle" || this.dbtype == "db2") {
                                    relationAndVal += " AND ','||" + tablename + "." + fieldname + "||',' not like '%," + fieldvaluevar[i] + ",%'";
                                }
                                if (this.dbtype == "sqlserver") {
                                    relationAndVal += " AND ','+isnull(cast(" + tablename + "." + fieldname + " as varchar(4000)),'')+',' not like '%," + fieldvaluevar[i] + ",%'";
                                }
                            }
                        }
                        text = " not like " + "'%" + fieldtext + "%'";
                    } else {
                        var isneedf = true;
                        if (htmltype == 4) {//checkbox
                            isneedf = false;
                        } else if (htmltype == 1 && (fieldtype == 2 || fieldtype == 3)) {//整数浮点数
                            isneedf = false;
                        } else if (htmltype == 5 && fieldtype == 2) {
                            isneedf = true;
                        } else if (htmltype == 5) {//select框
                            isneedf = false;
                        }

                        let compareoptionStr = "";
                        if (compareopion == "0") {
                            compareoptionStr = ">";
                        } else if (compareopion == "1") {
                            compareoptionStr = ">=";
                        } else if (compareopion == "2") {
                            compareoptionStr = "<";
                        } else if (compareopion == "3") {
                            compareoptionStr = "<=";
                        } else if (compareopion == "4") {
                            compareoptionStr = "=";
                        } else if (compareopion == "5") {
                            compareoptionStr = "!=";
                        } else if (compareopion == "100") {
                            compareoptionStr = "like";
                        }
                        if (isneedf) {
                            relationAndVal = compareoptionStr + " '" + fieldvalue + "'";
                        } else {
                            relationAndVal = compareoptionStr + " " + fieldvalue;
                        }
                        text = compareoptionStr + " '" + fieldtext + "'";
                    }
                    if (compareopion == 6 || compareopion == 7) {
                        sql += "( " + relationAndVal + " )";
                    } else {
                        sql += tablename + "." + fieldname + " " + relationAndVal;
                    }
                    sqlText += fieldlabel + " " + text;
                } else {

                    let fieldvalueObj = "";
                    if (fieldtype == '256') {//自定义树形
                        let fieldvaluevar = fieldvalue.split(",");
                        for (let i = 0; i < fieldvaluevar.length; i++) {
                            fieldvalueObj += "'" + fieldvaluevar[i] + "',"
                        }
                        fieldvalueObj = fieldvalueObj.substring(0, fieldvalueObj.length - 1);
                    }
                    if (compareopion == 6) {//包含
                        relationAndVal = " like " + "'%" + fieldvalue + "%'";
                        text = " like " + "'%" + fieldtext + "%'";
                    } else if (compareopion == 7) {//不包含
                        relationAndVal = " not like '%" + fieldvalue + "%'";
                        text = " not like " + "'%" + fieldtext + "%'";
                    } else if (compareopion == 8) {//属于
                        if (fieldtype == '256') {
                            relationAndVal += " in (" + fieldvalueObj + ")";
                        } else {
                            relationAndVal += " in (" + fieldvalue + ")";
                        }
                        text = " in " + "(" + fieldtext + ")";
                    } else if (compareopion == 9) {//不属于
                        if (fieldtype == '256') {
                            relationAndVal += " not  in (" + fieldvalueObj + ")";
                        } else {
                            relationAndVal += " not  in (" + fieldvalue + ")";
                        }
                        text = " not  in " + "(" + fieldtext + ")";
                    } else if (compareopion == 10) {//属于(含下级)
                        relationAndVal += " in (" + fieldvalue + ")";
                        text = getLabel(82763, "属于(含下级)") + "(" + fieldtext + ")";
                    } else if (compareopion == 11) {//属于(不含下级)
                        relationAndVal += " not  in (" + fieldvalue + ")";
                        text = getLabel(82764, "不属于(含下级)") + "(" + fieldtext + ")";
                    } else {
                        var isneedf = true;
                        if (htmltype == 4) {//checkbox
                            isneedf = false;
                        } else if (htmltype == 1 && (fieldtype == 2 || fieldtype == 3)) {//整数浮点数
                            isneedf = false;
                        } else if (htmltype == 5) {//select框
                            isneedf = false;
                        }

                        let compareoptionStr = "";
                        if (compareopion == "0") {
                            compareoptionStr = ">";
                        } else if (compareopion == "1") {
                            compareoptionStr = ">=";
                        } else if (compareopion == "2") {
                            compareoptionStr = "<";
                        } else if (compareopion == "3") {
                            compareoptionStr = "<=";
                        } else if (compareopion == "4") {
                            compareoptionStr = "=";
                        } else if (compareopion == "5") {
                            compareoptionStr = "!=";
                        } else if (compareopion == "100") {
                            compareoptionStr = "like";
                        }
                        if (isneedf) {
                            relationAndVal = compareoptionStr + " '" + fieldvalue + "'";
                        } else {
                            relationAndVal = compareoptionStr + " " + fieldvalue;
                        }
                        text = compareoptionStr + " '" + fieldtext + "'";
                    }
                    // sql +=  tablename+"."+ fieldname+" "+relationAndVal;
                    sql += fieldlabel + " " + relationAndVal;
                    sqlText += fieldlabel + " " + text;
                }
            }

        }
        return { sql, sqlText };
    }

    @action
    getRelationArr = (relationtype, type) => {
        let arr = new Array();
        if (relationtype == "1") {
            arr = [{
                key: "4",
                showname: getLabel(327, "等于"),
            }, {
                key: "5",
                showname: getLabel(15506, "不等于"),
            }, {
                key: "6",
                showname: getLabel(346, "包含"),
            }, {
                key: "7",
                showname: getLabel(15507, "不包含"),
            }];
        } else if (relationtype == "2") {
            arr = [{
                key: "0",
                showname: getLabel(15508, "大于"),
            }, {
                key: "1",
                showname: getLabel('513501','大于或等于'),
            }, {
                key: "2",
                showname: getLabel(15509, "小于"),
            }, {
                key: "3",
                showname: getLabel('513502','小于或等于'),
            }, {
                key: "4",
                showname: getLabel(327, "等于"),
            }, {
                key: "5",
                showname: getLabel(15506, "不等于"),
            }];
        } else if (relationtype == "3") {
            if (type == "2") {
                arr = [{
                    key: "6",
                    showname: getLabel(346, "包含"),
                }, {
                    key: "7",
                    showname: getLabel(15507, "不包含"),
                }];
            } else {
                arr = [{
                    key: "4",
                    showname: getLabel(327, "等于"),
                }, {
                    key: "5",
                    showname: getLabel(15506, "不等于"),
                }];
            }
        } else if (relationtype == "4") {
            if (type == "17" || type == "18" || type == "37" || type == "57" || type == "65" || type == "135" || type == "152" || type == "162"
                || type == "166" || type == "168" || type == "170" || type == "184" || type == "194" || type == "257" || type == "261"
                || type == "269" || type == "278") {
                arr = [{
                    key: "6",
                    showname: getLabel(346, "包含"),
                }, {
                    key: "7",
                    showname: getLabel(15507, "不包含"),
                }];
            } else {
                arr = [{
                    key: "4",
                    showname: getLabel(327, "等于"),
                }, {
                    key: "5",
                    showname: getLabel(15506, "不等于"),
                }];
                if (type == "1" || type == "165" || type == "167" || type == "169" || type == "16" || type == "9"
                    || type == "7" || type == "8" || type == "24" || type == "161" || type == "256" || type == "87" || type == "292" || type == "270") {
                    arr.push({
                        key: "8",
                        showname: getLabel(353, "属于"),
                    },
                        {
                            key: "9",
                            showname: getLabel(21473, "不属于"),
                        });
                }
                if (type == "4" || type == "164") {
                    arr.push({
                        key: "8",
                        showname: getLabel(353, "属于"),
                    },
                        {
                            key: "9",
                            showname: getLabel(21473, "不属于"),
                        }, {
                            key: "10",
                            showname: getLabel(82763, "属于(含下级)"),
                        }, {
                            key: "11",
                            showname: getLabel(82764, "不属于(含下级)"),
                        }
                    );
                }

            }
        }
        return arr;
    }

    @action
    onShow = () => {
        this.visable = true;
    }

    @action
    onCancel = () => {
        this.visable = false;
        this.parent().reEnterCell();
    }

    @action
    initCondition = (fieldProps, dsid, targetValueOptions, tableOptions) => {
        getDataCondition(dsid).then((data) => {
            this.setFieldOptions(data, fieldProps, targetValueOptions, tableOptions);
        });
    }

    @action
    setFieldOptions = (data, fieldProps, targetValueOptions, tableOptions) => {
        this.targetValueOptions = targetValueOptions;
        this.fieldRecord = {};
        this.fieldPropsStore = fieldProps;
        const cellType = fieldProps.cellType();
        this.conditionInfo = {
            conditiontype: "1",
            conditionsql: "",
            conditiontext: "",
            conditionsql2: "",
            fieldOptions: data
        }
        this.root = {};
        if (cellType) {
            const { conditionInfo } = cellType;
            if (conditionInfo) {
                const { conditiontype, conditionsql, conditiontext, conditionsql2, root } = conditionInfo;
                if (conditiontype) {
                    if (conditiontype === "1") {
                        this.conditionInfo = {
                            conditiontype: conditiontype,
                            conditionsql: conditionsql,
                            conditiontext: conditiontext,
                            conditionsql2: "",
                            fieldOptions: data
                        }
                        this.root = conditionInfo.root;
                    } else if (conditiontype === "2") {
                        this.conditionInfo = {
                            conditiontype: conditiontype,
                            conditionsql2: conditionsql2,
                            conditionsql: "",
                            conditiontext: "",
                            fieldOptions: data
                        }
                        this.root = {};
                    }
                }
            }
        }
        this.conditionField = {};
        this.targetValue = "";
        this.targetValueSpan = "";
        this.ismodified = "0";
        this.valuetype = "";
        this.selectedItemKey = [];
        this.editArr = [];
        this.selectedItemParentNode = "";
        this.ruleSql = "";
        this.isShowSql = false;
        this.isChange = false;
        this.isNeedClose = false;
        this.tableOptions = tableOptions;
        this.onShow();
    }

    @action
    changeFieldValue = (key, value) => {
        const conditionInfo = this.conditionInfo;
        const { fieldOptions } = conditionInfo;
        let options = this.getFieldOptions(fieldOptions);
        if (key == "targetFieldid") {
            this.targetValue = "";
            this.targetValueSpan = "";
            if (value != "") {
                for (let i = 0; i < options.length; i++) {
                    if (options[i].key == value) {
                        this.fieldRecord = options[i];
                        this.getRelationtypeOption();
                        break;
                    }
                }
            } else {
                this.fieldRecord = {};
            }
            this.relation = "4";
            this.isChange = true;
        } else if (key == "conditiontype") {
            this.changeModified();
            // conditionInfo.conditiontype = value;
            this.conditionInfo = {
                ...conditionInfo,
                conditiontype: value
            };
        } else if (key == "relation") {
            this.relation = value;
            this.isChange = true;
        } else if (key == "conditionsql2") {
            this.conditionInfo = {
                ...conditionInfo,
                conditionsql2: value
            };
            this.changeModified();
        } else if (key == "targetFieldid_") {
            this.targetValue = value;
        } else if (key == "valuetype") {
            this.valuetype = value;
        } else if (key == "targetValue") {
            this.targetValue = value;
            this.fieldRecord.valueshowtype = 5;
        }
    }

    @action
    getRelationtypeOption = () => {
        const fieldRecord = this.fieldRecord;
        const { relationtype } = fieldRecord;
        const { type } = fieldRecord;
        let arr = this.getRelationArr(2, type);
        this.relationtypeOptions = arr;
    }

    @action
    getSelectedObj(key, array) {
        let obj = undefined;
        for (let i = 0; i < array.length; i++) {
            if (key == array[i].key) {
                obj = array[i];
                break;
            }
        }
        return obj;
    }

    @action
    getValue4Obj = () => {
        const { valueshowtype, showname } = this.fieldRecord;
        const relation = this.relation;
        let fieldlabel = showname;
        let valetype = valueshowtype;
        let compareopion = this.relation;
        let relationtypeOptions = this.relationtypeOptions;
        let compareopionlabel = "";
        let selectObj = this.getSelectedObj(relation, relationtypeOptions);
        if (selectObj) {
            compareopionlabel = selectObj["showname"];
        }
        //value span 取值
        let fieldvalue = this.targetValue;
        let fieldtext = this.targetValue;
        if (valetype == 5) {//下拉框
            selectObj = this.getSelectedObj(this.targetValue, this.targetValueOptions);
            if (selectObj) {
                fieldtext = selectObj["showname"];
            }
        }

        //组装字符串 显示和后台所需
        var hiddenarea = {
            key: new Date().getTime(),
            fieldlabel: fieldlabel,
            compareopion: compareopion,
            compareopionlabel: compareopionlabel,
            fieldvalue: fieldvalue,
            fieldtext: fieldtext,
            valetype: valetype,
            fieldOldvalue: '',
        };
        return hiddenarea;
    }

    //拼接条件显示 方法
    @action
    showDisplaySpan = (areaJson) => {
        const { htmltype, fieldtype, fieldlabel } = areaJson;
        let text = "'" + areaJson.fieldtext + "'";
        if (htmltype == "1") {
            if (fieldtype != "1") {
                text = areaJson.fieldtext;
            }
        }
        var displayspan = fieldlabel + " " + areaJson.compareopionlabel + " " + text;
        return displayspan;
    }

    @action
    getNode = (area, pid) => {
        let noded = {
            isParent: false,
            parentNode: pid,
            ...area
        };
        return noded;
    }

    @action
    addParam = (o) => {
        const refObj = this.refObj;
        const fieldRecord = this.fieldRecord;
        const targetValue = this.targetValue;
        if (!(fieldRecord && fieldRecord.key)) {
            for (let key in refObj) {
                if (key == "mbzd") {
                    const domkeyRef = refObj[key];
                    domkeyRef.showError();
                    return;
                }

            }
        }
        if (_.trim(formatMultiLang(targetValue)) == "") {
            for (let key in refObj) {
                if (key == "mbzd_") {
                    const domkeyRef = refObj[key];
                    domkeyRef.showError();
                    return;
                }

            }
        }


        var area = this.getValue4Obj();
        if (area.htmltype == 5 && area.fieldtype == 2) {
            if (targetValue.indexOf("null") != -1 && targetValue != "null") {
                message.error(getLabel(390017, "复选框null和其他不能同时勾选"));
                return;
            }
        }
        if (this.selectedItemKey.length > 0) {
            area.parentNode = this.selectedItemParentNode;
            this.addToTree(this.root, area);
        } else {
            if (this.root && this.root.key) {
                area.parentNode = this.root.key;
                let node = this.getNode(area, this.root.key);
                const { datas, ...props } = this.root;
                datas.push(node);
                this.root = { ...props, datas: datas }
            } else {
                let k = new Date().getTime();
                let node = this.getNode(area, k);
                let obj = { key: k, relationship: "1", isParent: true, parentNode: "", datas: [node] };
                this.root = obj;
            }
        }
        this.isChange = false;
        this.getRuleSql();
        this.changeModified();
        let contentScroll = o.refs.contentScroll;
        setTimeout(() => {
            contentScroll["scrollToLast"]();
        }, 100)
    }

    @action
    addToTree = (item, area) => {
        const { isParent, key, datas,  ...props } = item;
        let flag = false;
        if (isParent) {//父节点
            if (this.selectedItemParentNode == key) {
                let node = this.getNode(area, key);
                datas.push(node);
                let obj = { key: key, isParent: isParent, datas, ...props };
                this.root = obj;
                flag = true;
            } else {
                for (let i = 0; i < datas.length; i++) {
                    if (this.addToTree(datas[i], area, datas)) {
                        break;
                    }
                }
            }
        }
        return flag;
    }

    @action
    changeModified = () => {
        this.ismodified = "1";
    }

    @action
    timer = () => { setTimeout(() => { }, 1000) };

    @action
    switchSelected = (e, areaJson) => {
        const { parentNode } = areaJson;
        if (this.selectedItemParentNode != parentNode) {
            this.selectedItemKey = [areaJson.key];
        } else {
            this.selectedItemKey = this.selectedItemKey.indexOf(areaJson.key) === -1
                ? [...this.selectedItemKey, areaJson.key] :
                this.selectedItemKey.filter(d => d !== areaJson.key);
        }
        this.selectedItemParentNode = areaJson.parentNode;
    }

    @action
    switchSelectedDiv(e, areaJson) {
        if (e.target) {//阻止事件冒泡
            let id = e.target.getAttribute("id");
            if (id && (id == "relationblock_" + areaJson.key || id == "relationItem_" + areaJson.key)) {
                this.switchSelected(e, areaJson);
            }
        }

    }

    @action
    delFromArray = (array, selectRowIds) => {
        for (let i = 0; i < selectRowIds.length; i++) {
            let key = selectRowIds[i];
            for (let j = 0; j < array.length; j++) {
                if (array[j]["key"] == key) {
                    array.splice(j, 1);
                    break;
                }
            }
        }
        return array;
    }

    @action
    cancelBackFun = (areaJson) => {
        if (areaJson) {
            this.delFromArray(this.editArr, [areaJson.key]);
        }
        this.getRuleSql();
    }

    @action
    toEditItem = (areaJson) => {
        clearTimeout(this.timer);
        areaJson.isEdit = 1;
        this.changeContentHeight();
        this.selectedItemKey = [];
        this.selectedItemParentNode = "";
        this.editArr.push(areaJson);
    }

    @action
    switchRelationEditMode = (itemObj) => {
        let { relationship } = itemObj;
        this.root = this.setTelationship(this.root, itemObj.key)
        this.getRuleSql();
    }

    @action setTelationship = (root, key) => {
        if (root.key === key) {
            return {
                ...root,
                relationship: root.relationship === "0" ? "1" : "0"
            }
        } else {
            return {
                ...root,
                datas: root.datas.map(d => {
                    if (d.isParent) {
                        return this.setTelationship(d, key);
                    } else {
                        return { ...d };
                    }
                })
            }
        }
    }
    //返回表达式显示文字
    @action
    expressdescElement = (areaJson) => {
        let selectedItemKey = this.selectedItemKey;
        let selectedCss = "";
        selectedItemKey = selectedItemKey.slice(0);
        if (selectedItemKey.indexOf(areaJson.key) > -1) {
            selectedCss = " spanselected";
        }
        var displayspan = this.showDisplaySpan(areaJson)
        const { key } = areaJson;
        return (
            <span onClick={(e) => this.switchSelected(e, areaJson)}
                onDoubleClick={(e) => this.toEditItem(areaJson)} className={'displayspan' + selectedCss} key={key} >
                {displayspan}
            </span>)

    };

    //添加条件 (0:或/1：与)
    @action
    addbracket = (relationship) => {
        const selectedItemKey = this.selectedItemKey;
        const selectedItemParentNode = this.selectedItemParentNode;
        const root = this.root;
        if (selectedItemKey.length < 2) {
            return;
        }
        var childsum = $("#relationblock_" + selectedItemParentNode).children(".relationItem").length;
        if (childsum == selectedItemKey.length) {
            message.error(getLabel('513504','关系已存在'));
            return;
        }
        this.changeData(root, relationship);
        this.selectedItemKey = [];
        this.selectedItemParentNode = "";
        this.getRuleSql();
        this.changeModified();
    };

    @action
    changeData = (item, relationship) => {
        const selectedItemKey = this.selectedItemKey;
        const selectedItemParentNode = this.selectedItemParentNode;
        const { key, isParent, datas } = item;
        let flag = false;
        if (isParent) {
            if (key == selectedItemParentNode) {
                let newArray = new Array();
                let selectArr = new Array();
                let firstIndex = -1;//第一次出现的位置
                let newKey = new Date().getTime();
                let oldParentNode = "";
                for (let i = 0; i < datas.length; i++) {
                    let isSelected = false;//是否被选中
                    for (let j = 0; j < selectedItemKey.length; j++) {
                        if (selectedItemKey[j] == datas[i].key) {
                            isSelected = true;
                            break;
                        }
                    }
                    if (isSelected) {
                        if (firstIndex == -1) {
                            firstIndex = i;
                            oldParentNode = datas[i].parentNode;
                        }
                        datas[i].parentNode = newKey;
                        selectArr.push(datas[i]);
                    } else {
                        newArray.push(datas[i]);
                    }
                }
                let newNode = { key: newKey, relationship: relationship, isParent: true, parentNode: oldParentNode, datas: selectArr };
                newArray.splice(firstIndex, 0, newNode);
                item.datas = newArray;
                flag = true;
            } else {
                for (let i = 0; i < datas.length; i++) {
                    if (this.changeData(datas[i], relationship)) {
                        break;
                    }
                }
            }
        }
        return flag;
    }

    //删除已有并选中的条件
    @action
    delParam = () => {
        const selectedItemKey = this.selectedItemKey;
        const root = this.root;
        if (selectedItemKey.length > 0) {
            let deleteData = this.deleteData;
            let getRuleSql = this.getRuleSql;
            Modal.confirm({
                title: getLabel('513503','确认要删除选中记录吗？'),
                onOk: () => {
                    deleteData(root);
                    this.selectedItemKey = [];
                    this.selectedItemParentNode = "";
                    getRuleSql();
                },
                onCancel() { },
            });
            this.changeModified();
        }

    }

    @action
    deleteData = (item) => {
        const selectedItemKey = this.selectedItemKey;
        const selectedItemParentNode = this.selectedItemParentNode;
        const root = this.root;
        const { key, isParent, datas, parentNode } = item;
        let flag = false;
        if (isParent) {
            if (key == selectedItemParentNode) {
                let remainArray = new Array();//剩余的数据
                for (let i = 0; i < datas.length; i++) {
                    let isSelected = false;//是否被选中
                    for (let j = 0; j < selectedItemKey.length; j++) {
                        if (selectedItemKey[j] == datas[i].key) {
                            isSelected = true;
                            break;
                        }
                    }
                    if (!isSelected) {
                        remainArray.push(datas[i]);
                    }
                }
                if (remainArray.length > 0) {//剩余还有数据
                    item.datas = remainArray;
                } else {//剩余没有数据
                    if (parentNode == "") {
                        this.root = {};
                    } else {
                        this.deleteParentNode(root, key, parentNode, root);//所有子项都被选中，则删除item节点本身
                    }
                }

                flag = true;
            } else {
                for (let i = 0; i < datas.length; i++) {
                    if (this.deleteData(datas[i])) {
                        break;
                    }
                }
            }
        }
        return flag;
    }

    @action
    deleteParentNode = (item, nodeid, parentid, parent) => {
        const { key, isParent, datas } = item;
        let flag = false;
        if (isParent) {
            if (key == parentid) {
                let datasArray = parent.datas;
                for (let i = 0; i < datasArray.length; i++) {
                    if (nodeid == datasArray[i].key) {
                        datasArray.splice(i, 1);
                        flag = true;
                        break;
                    }
                }
            }
        } else {
            for (let i = 0; i < datas.length; i++) {
                if (this.deleteParentNode(datas[i], key, parentid, item)) {
                    break;
                }
            }
        }
        return flag;
    }

    //拆分条件
    @action
    splitCondition = () => {
        const selectedItemKey = this.selectedItemKey;
        // const root = this.root;
        if (selectedItemKey.length > 0) {
            this.splitChangeData(this.root);
            this.selectedItemKey = [];
            this.selectedItemParentNode = "";
        }
        this.getRuleSql();
        this.changeModified();
    }

    @action
    splitChangeData = (item) => {
        const selectedItemKey = this.selectedItemKey;
        const selectedItemParentNode = this.selectedItemParentNode;
        const { key, isParent, datas } = item;
        let flag = false;
        if (isParent) {
            if (key == selectedItemParentNode) {
                let newArray = new Array();//剩余的数据
                for (let i = 0; i < datas.length; i++) {
                    let isSelected = false;//是否被选中
                    for (let j = 0; j < selectedItemKey.length; j++) {
                        if (selectedItemKey[j] == datas[i].key) {
                            isSelected = true;
                            break;
                        }
                    }
                    if (!isSelected) {
                        newArray.push(datas[i]);
                    } else {
                        let newDatas = this.getNewDatas(key, datas[i]);
                        newArray = newArray.concat(newDatas.slice());
                    }
                }
                this.root.datas = newArray;
                flag = true;
            } else {
                for (let i = 0; i < datas.length; i++) {
                    if (this.splitChangeData(datas[i])) {
                        break;
                    }
                }
            }
        }
        return flag;
    }

    @action
    getNewDatas = (pid, item) => {
        const { datas } = item;
        for (let i = 0; i < datas.length; i++) {
            datas[i].parentNode = pid;
        }
        return datas;
    }


    @action
    getRelationItems = (itemObj, isRoot) => {
        if (itemObj && itemObj.datas && itemObj.datas.length > 0) {
            const { key, relationship, datas } = itemObj;
            let relationDesc = "AND";
            if (relationship == "0") {
                relationDesc = "OR";
            }
            let selectedItemKey = this.selectedItemKey;
            let selectedCss = "";
            let title = "";
            title = getLabel(384567, "双击更改关系");
            selectedItemKey = selectedItemKey.slice(0);
            if (!isRoot) {
                if (selectedItemKey.indexOf(itemObj.key) > -1) {
                    selectedCss = " spanselected";
                }
            } else {
                selectedCss = " isroot";
            }


            return <div id={"relationblock_" + key} onClick={(e) => { if (!isRoot) { this.switchSelectedDiv(e, itemObj) } }} className={"relationblock" + selectedCss} key={key}>
                <div className="verticalblock" title={title} onDoubleClick={() => { this.switchRelationEditMode(itemObj) }}>{relationDesc}</div>
                <div className="relationStyle outermoststyle" >
                    <div className="relationStyleTop"></div>
                    <div className="relationStyleCenter"></div>
                    <div className="relationStyleBottom"></div>
                </div>
                {datas.map((item) => {
                    const { isParent } = item;
                    if (isParent) {
                        return <div className="relationItem">{this.getRelationItems(item, false)}</div>;
                    } else {
                        const { isEdit } = item;
                        if (isEdit && isEdit == 1) {

                        } else {
                            return <span className="relationItem" id={"relationItem_" + key}
                                onClick={(e) => { if (!isRoot) { this.switchSelectedDiv(e, itemObj) } }}>
                                {this.expressdescElement(item)}
                            </span>

                        }
                    }
                })}

            </div>;
        }
        return <div></div>;
    }

    @action
    changeContentHeight = () => {
        let dialogHeight = 616;
        let h = dialogHeight * 0.9 - 115;
        const isShowSql = this.isShowSql;
        let h1 = 51;
        if ($(".wev-cube-condition-top").outerHeight() > 51) {
            h1 = $(".wev-cube-condition-top").outerHeight();
        }
        let h2 = 50;
        let h3 = 0;
        if (isShowSql) {
            h3 = 65;
        }
        h = dialogHeight * 0.9 - h1 - h2 - h3;
        this.contentHeight = h;
    }

    @action
    getRuleSql = () => {
        const isShowSql = this.isShowSql;
        if (isShowSql) {
            this.getShowSql();
        }
    }

    @action
    changeShowSql = () => {
        const isShowSql = this.isShowSql;
        this.isShowSql = !isShowSql;
        this.changeContentHeight();
        this.getRuleSql();
    }

    /**
    * 根据选择框的名称，搜索过滤选项
     * @param inputValue 
     * @param option 
    */
    @action
    selectFilterOption = (inputValue, option) => {
        if (inputValue != "") {
            const { children } = option["props"];
            if (children) {
                if ((typeof children) == "string") {
                    return children.toLowerCase().indexOf(inputValue.toLowerCase()) != -1;
                } else if ((typeof children) == "object" && children.length > 0) {
                    const childrenNew = children[0]["props"]["children"];
                    if (childrenNew) {
                        return childrenNew.toLowerCase().indexOf(inputValue.toLowerCase()) != -1;
                    } else {
                        return false;
                    }
                } else {
                    const childrenNew = children["props"]["children"];
                    if (childrenNew) {
                        return childrenNew.toLowerCase().indexOf(inputValue.toLowerCase()) != -1;
                    } else {
                        return false;
                    }
                }
            } else {
                return false;
            }
        }
        return true;
    }

    @action
    getFieldOptions = (fields) => {
        const options = [];
        if (fields && fields.length > 0) {
            fields.forEach(d => {
                options.push({
                    key: `${d.name}`,
                    showname: `${d.text}`
                });
            });
        }
        return options;
    }
}